package com.lean.android.ad.workflow

import androidx.annotation.RestrictTo
import com.lean.android.ad.utils.AdLog

@RestrictTo(RestrictTo.Scope.LIBRARY)
class SequenceWorkFlow(
    private val nodes: List<WorkFlowNode>, private val onComplete: () -> Unit = {}
) : WorkFlow {

    private var currentNode: WorkFlowNode? = null

    override fun start() {
        currentNode = nodes.firstOrNull {
            it.enterCondition()
        }
        currentNode?.enter(this)
    }

    override fun next() {
        if (currentNode == null) {
            AdLog.e(AdLog.AdWorkFlowTag, "current node is null, forget to call start() ? ")
            return
        }
        val currentIndex = nodes.indexOf(currentNode)
        if (currentIndex == -1) return
        val node = nodes.withIndex().firstOrNull {
            it.index > currentIndex && it.value.enterCondition()
        }?.value

        currentNode = node

        if (node == null) {
            AdLog.d(AdLog.AdWorkFlowTag, "nextNode not found, work flow exit.")
            onComplete()
        } else {
            AdLog.d(AdLog.AdWorkFlowTag, "nextNode found, ready to enter.")
            node.enter(this)
        }
    }
}